package javatest.guisender;

import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core;
import com.messaging.UdpMq;
import com.vpx.VpxEncoder;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javatest.ByteOutputStream;
import javatest.Utils;
import javax.swing.Timer;

/**
 *
 * @author sad
 */
public class UdpSenderForm extends javax.swing.JFrame {

    private OpenCVFrameGrabber grabber;
    private opencv_core.IplImage cameraImage;
    private Timer timer;
    private UdpMq mq;
    private VpxEncoder encoder;
    private final ByteOutputStream byteStream = new ByteOutputStream(20000);
    private int counter = 0;
    private InetAddress address;
    private short sessionId = (short) (Math.random() * 65535);
    private final int clientCount =10;
    private final int remotePort = 5557;

    /**
     * Creates new form UdpSender
     */
    public UdpSenderForm() {
        initComponents();
        initCodec();
        Timer tTimer = new Timer(100, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (mq != null) {
                    queuedLabel.setText("" + mq.getMessageQueuedCount());
                    mpsLabel.setText("" + mq.getCurrentMessagePerSeconds());
                }
            }
        });
        tTimer.setRepeats(true);
        tTimer.start();
    }

    private void paintCamPanel(Graphics gr) {
        if (cameraImage != null) {
            gr.drawImage(cameraImage.getBufferedImage(), cameraPanel.getWidth() / 2 - cameraImage.width() / 2, cameraPanel.getHeight() / 2 - cameraImage.height() / 2, cameraPanel);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        startButton = new javax.swing.JButton();
        cameraPanel = new javax.swing.JPanel(){
            public void paint(Graphics gr){
                super.paint(gr);
                paintCamPanel(gr);
            }
        };
        ipField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        stopButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        queuedLabel = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        mpsLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("Camera");

        startButton.setText("Start");
        startButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startButtonActionPerformed(evt);
            }
        });

        cameraPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        cameraPanel.setPreferredSize(new java.awt.Dimension(330, 250));

        javax.swing.GroupLayout cameraPanelLayout = new javax.swing.GroupLayout(cameraPanel);
        cameraPanel.setLayout(cameraPanelLayout);
        cameraPanelLayout.setHorizontalGroup(
            cameraPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 328, Short.MAX_VALUE)
        );
        cameraPanelLayout.setVerticalGroup(
            cameraPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 248, Short.MAX_VALUE)
        );

        ipField.setText("192.168.1.100");

        jLabel2.setText("ip");

        stopButton.setText("Stop");
        stopButton.setEnabled(false);
        stopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopButtonActionPerformed(evt);
            }
        });

        jLabel3.setText("Queued:");

        queuedLabel.setText("          ");

        jLabel4.setText("MPS:");

        mpsLabel.setText("          ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cameraPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(ipField)
                            .addComponent(startButton, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                            .addComponent(stopButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(queuedLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addGap(18, 18, 18)
                                        .addComponent(mpsLabel)))
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(3, 3, 3)
                        .addComponent(cameraPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ipField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(startButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stopButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(queuedLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(mpsLabel))))
                .addContainerGap(65, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void startUdpServer() {
        mq = new UdpMq(5555);
        mq.start();
    }

    private void initCodec() {
        encoder = new VpxEncoder(160, 120, VpxEncoder.calculateBasicFrameRate(160, 120), 20);
    }

    private void sendConnectClientReliableMessage(short clientId) {
        ByteOutputStream stream = new ByteOutputStream(60);
        stream.writeByte((byte) 1);//client Connect type
        stream.writeShort(clientId);//client id
        stream.writeShort(sessionId);
        System.out.println("Session " + sessionId);
          mq.sendMessageReliable(stream.toByteArray(), address, remotePort);
    }

    private void sendPicToClient(opencv_core.IplImage image) {
        byteStream.reset();
        byteStream.writeByte((byte) 0);//video frame
        byteStream.writeShort((short) 0);//client number
        byteStream.writeInt(counter);//frame index
        encoder.encodeImage(image, byteStream);
        byte[] array = byteStream.toByteArray();
        for (int i = 0; i < clientCount; i++) {
            Utils.arrayPutShort(array, 1, (short) i);
            mq.sendMessage(array, address, remotePort);
            /*if ((counter % 5) == 0) {
             try {
             Thread.sleep(1);
             } catch (InterruptedException ex) {
             ex.printStackTrace();
             }
             }*/
        }
        counter++;
    }

    private void registerClients() {
        for (int i = 0; i < clientCount; i++) {
            sendConnectClientReliableMessage((short) i);
        }

          while (mq.getWaitAcksCount() > 0) {
         try {
         Thread.sleep(50);
         } catch (InterruptedException ex) {
         ex.printStackTrace();
         }
         }
        System.out.println("All Clients responded");
    }

    private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
        try {
            sessionId = (short) (Math.random() * 65535);
            address = InetAddress.getByName(ipField.getText());
            if (grabber == null) {
                grabber = new OpenCVFrameGrabber(0);
                grabber.setImageWidth(320);
                grabber.setImageHeight(240);
            }
            grabber.start();
            timer = new Timer(33, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        step();
                    } catch (FrameGrabber.Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });

            timer.setRepeats(true);
            timer.start();
            startButton.setEnabled(false);
            ipField.setEnabled(false);
            stopButton.setEnabled(true);
            startUdpServer();
            registerClients();
        } catch (FrameGrabber.Exception | UnknownHostException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_startButtonActionPerformed

    private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed
        try {
            if (grabber != null) {
                grabber.stop();
            }
            if (timer != null) {
                timer.stop();
                timer = null;
            }
            cameraImage = null;
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            cameraPanel.repaint();
            ipField.setEnabled(true);
            //if (mq != null) {
            //    mq.stop();
            //}
        } catch (FrameGrabber.Exception ex) {
            Logger.getLogger(UdpSenderForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_stopButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        stopButtonActionPerformed(null);
    }//GEN-LAST:event_formWindowClosing

    private void step() throws FrameGrabber.Exception {
        cameraImage = grabber.grab();
        opencv_core.IplImage image = opencv_core.IplImage.create(opencv_core.cvSize(160, 120), 8, 3);
        opencv_core.cvSetImageROI(cameraImage, opencv_core.cvRect(50, 50, 160, 120));
        opencv_core.cvCopy(cameraImage, image);
        opencv_core.cvSetImageROI(cameraImage, opencv_core.cvRect(0, 0, 320, 240));
        cameraPanel.repaint();
        sendPicToClient(image);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel cameraPanel;
    private javax.swing.JTextField ipField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel mpsLabel;
    private javax.swing.JLabel queuedLabel;
    private javax.swing.JButton startButton;
    private javax.swing.JButton stopButton;
    // End of variables declaration//GEN-END:variables
}
